package vote.ai.service.Impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import vote.ai.domain.entity.UserCorrectionCharLimit;
import vote.ai.mapper.UserCorrectionCharLimitMapper;
import vote.ai.service.CorrectionCharLimitService;
import vote.util.BusinessException;

/**
 * Description:用户纠错字符限制服务
 * Author:han
 * Date: 2024-05-21
 */
@Service
public class UserCorrectionCharLimitServiceImpl implements CorrectionCharLimitService {
    @Resource
    private UserCorrectionCharLimitMapper userCorrectionCharLimitMapper;

    @Override
    public UserCorrectionCharLimit getUserCharLimit(long userId) {
        UserCorrectionCharLimit userCorrectionCharLimit = userCorrectionCharLimitMapper.selectById(userId);
        if (ObjectUtils.isEmpty(userCorrectionCharLimit)) {
            throw new BusinessException("暂未配置纠错服务的使用次数，请联系管理员!");
        }//todo  han 2025-05-08 判断当前是否有可用字符数
        return userCorrectionCharLimit;
    }

    @Override
    public void userChar(long userId, int charLength) {
        if (charLength <= 0) {
            return;
        }
        LambdaUpdateWrapper<UserCorrectionCharLimit> updateWrapper = new LambdaUpdateWrapper<>();
        // 设置更新的 SQL 语句，增加已使用字符数 利用行锁 乐观锁 原子更新
        // update x t set t.used_char_limit = t.used_char_limit + charLength where t.user_id = userId and t.total_char_limit >= t.used_char_limit + charLength
        updateWrapper.setSql("used_char_limit = used_char_limit + " + charLength);
        // 根据用户 ID 进行更新
        updateWrapper.eq(UserCorrectionCharLimit::getUserId, userId);
        // 原子性地检查总字符限制是否足够
        updateWrapper.apply("total_char_limit >= used_char_limit + " + charLength);
        if (1 != this.userCorrectionCharLimitMapper.update(updateWrapper)) {
            throw new BusinessException("超出纠错服务使用次数限制，请联系管理员!");
        }
    }
}
